<?php

namespace App\Http\Controllers\Rent\Business;

use App\Http\Controllers\ShopController;
use App\Models\Business\Business as BusinessModel;
use App\Models\Business\Source as SourceModel;
use App\Models\Business\Collection as CollectionModel;
use App\Models\Product\Order\Order as OrderModel;
use App\Models\Config as ConfigModel;
use App\Models\Region as RegionModel;
use Illuminate\Support\Facades\Validator;
use App\Models\Ems as EmsModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;


class BaseController extends ShopController
{
    public function register()
    {
        $mobile = request('mobile','');
        $password = request('password','');

        // 生成密码盐
        $salt = build_randstr();

        $password = md5($password . $salt);

        // 封装数据
        $data = [
            'mobile' => $mobile,
            'password' => $password,
            'salt' => $salt
        ];

        // 客户来源
        $source = SourceModel::where('name','LIKE','%租赁%')->first();

        if($source)
        {
            $data['sourceid'] = $source['id'];
        }

        // 定义验证器
        $validate = [
            [
                'mobile' => ['required','unique:business','regex:/^1[356789]\d{9}$/'],
                'password' => ['required'],
                'salt' => ['required']
            ],
            [
                'mobile.required' => '手机号必填',
                'mobile.unique' => '手机号已注册',
                'mobile.regex' => '手机号格式错误',
                'password.required' => '密码必填',
                'salt.required' => '密码盐未知',
            ]
        ];

        // 创建验证器
        $validator = Validator::make($data,...$validate);

        if($validator->fails())
        {
           return $this->error($validator->errors()->first());
        }

        $result = BusinessModel::create($data);

        if($result === false)
        {
            return $this->error('注册失败');
        }else{
            return $this->success('注册成功');
        }
    }

    public function login()
    {
        $mobile = request('mobile','');
        $password = request('password','');

        $business = BusinessModel::where(['mobile' => $mobile])->first();

        if(!$business)
        {
            return $this->error('手机号未注册');
        }

        $password = md5($password . $business['salt']);

        if($password !== $business['password'])
        {
            return $this->error('密码错误');
        }

        $data = [
            'id' => $business['id'],
            'mobile' => $business['mobile'],
            'mobile_text' => $business['mobile_text'],
            'nickname' => $business['nickname'],
            'email' => $business['email'],
            'gender' => $business['gender'],
            'gender_text' =>$business['sex_text'],
            'province' => $business['province'],
            'city' => $business['city'],
            'district' => $business['district'],
            'region_text' => $business['region_text'],
            'auth' => $business['auth'],
            'avatar_cdn' => $business['avatar_cdn']
        ];

        return $this->success('登录成功',$data);
    }

    // public function index()
    // {
    //     $busid = request('busid',0);
    //     $productCount = CollectionModel::where('busid',$busid)->where('proid','<>',null)->count();
    //     $cateCount = CollectionModel::where('busid',$busid)->where('cateid','<>',null)->count();
    //     $orderCount = OrderModel::where('busid',$busid)->count();

    //     $data = [
    //         'productCount' => $productCount,
    //         'cateCount' => $cateCount,
    //         'orderCount' => $orderCount
    //     ];
        
    //     return $this->success('查询成功',$data);
    // }

    public function index()
    {
        $busid = request('busid','');

        $ProductCount = CollectionModel::where([['busid','=',$busid],['proid','<>','']])->count();
        $CateCount = CollectionModel::where([['busid','=',$busid],['cateid','<>','']])->count();
        $OrderCount = OrderModel::where(['busid' => $busid])->count();

        $data = [
            'ProductCount' => $ProductCount,
            'CateCount' => $CateCount,
            'OrderCount' => $OrderCount
        ];

        return $this->success('查询成功',$data);
    }

    public function send()
    {
        $business = request()->get('business');

        $email = request('email',$business['email']);

        if(empty($email))
        {
            return $this->error('邮箱不能为空');
        }

        // 条件数组
        $where = [
            'event' => 'email',
            'email' => $email,
            'times' => 0
        ];

        $Ems = EmsModel::where($where)->first();
        // return $Ems;
        if($Ems)
        {
            return $this->error('已发送验证码，请查看邮箱');
        }

        DB::beginTransaction();

        // 生成验证码
        $code = build_randstr(4);
        
        $EmsData = [
            'event' => 'email',
            'email' => $email,
            'times' => 0,
            'code' => $code,
            'ip' => request()->ip()
        ];

        $validate = [
            [
                'event'  => 'required',
                'email'   => 'required',
                'code' => 'required',
                'ip' => 'required',
            ],
            [
                'event.required' => '事件必填',
                'email.required'     => '邮箱必须填写',
                'code.required'   => '验证码未知', 
                'ip.required'   => 'ip地址未知', 
            ]
        ];

        $validator = Validator::make($EmsData,...$validate);

        if($validator->fails())
        {
            return $this->error($validator->errors()->first());
        }

        $EmsStatus = EmsModel::create($EmsData);
        
        $SendStatus = Mail::send('shop.business.email',['code' => $code],function($message) use ($email) {
            $message->to($email)->subject('租借平台');
        });

        if($EmsStatus === false || $SendStatus === false)
        {
            DB::rollBack();
            return $this->error('邮箱验证码发送收失败');
        }else{
            DB::commit();
            return $this->success('邮箱验证码发送成功');
        }
    }

    public function check()
    {
        $business = request()->get('business');
        $code = request('code','');
        $email = request('email',$business['email']);

        if(empty(trim($code)))
        {
            return $this->error('验证码不能为空');
        }

        if(empty($email))
        {
            return $this->error('邮箱不能为空');
        }

        $where = [
            'event' => 'email',
            'email' => $email,
            'code' => trim($code)
        ];

        $Ems = EmsModel::where($where)->first();

        if(!$Ems)
        {
            return $this->error('验证码错误');
        }

        // 开启事务
        DB::beginTransaction();

        // 更新用户认证字段
        $business->auth = '1';

        $BusinessStatus = $business->save();

        $EmsStatus = $Ems->delete();

        if($BusinessStatus === false || $EmsStatus === false)
        {
            DB::rollBack();
            return $this->error('认证失败');
        }else{
            DB::commit();
            return $this->success('认证成功');
        }
    }

    public function profile()
    {
        // return 111;
        $params = request()->input();
        // return $params;
        $business = request()->get('business');
        // return $business;
        $data = [
            'nickname' => $params['nickname'],
            'email' => $params['email'],
            'gender' => $params['gender'],
        ];

        if($params['email'] != $business['email'])
        {
            $data['auth'] = '0';
        }

        if(!empty($params['password']))
        {
            $repass = md5($params['password'] . $business['salt']);

            if($repass == $business['password'])
            {
                return $this->error('新密码与原密码一致');
            }

            $salt = build_randstr();

            $data['password'] = md5($params['password'] . $salt);
            $data['salt'] = $salt;
        }
        
        if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
        {
            $cdn = ConfigModel::where('name','url')->value('value');

            $url = env('SITE_URL',$cdn);

            $url = $url . '/base/business/upload';

            // 第一个参数属于文件路径 第二个参数是文件类型 第三个是文件名
            $file =  new \CURLFile($_FILES['avatar']['tmp_name'],$_FILES['avatar']['type'],$_FILES['avatar']['name']);
            
            $res = httpRequest($url,['avatar' => $file,'id' => $business['id']]);

            $avatar = json_decode($res,true);
            
            if($avatar['code'] === 0)
            {
                return $this->error($avatar['msg']);
            }

            $data['avatar'] = $avatar['data'];
        }
        
        // 地区
        $path = RegionModel::where('code',$params['code'])->value('parentpath');

        if(!$path)
        {
            return $this->error('所选地区不存在');
        }

        [$province,$city,$district] = explode(',',$path);

        $data['province'] = $province ?? null;
        $data['city'] = $city ?? null;
        $data['district'] = $district ?? null;
        
        $result = BusinessModel::where(['id' => $params['busid']])->update($data);
        // return $result;
        if($result === false)
        {
            if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                $cdn = ConfigModel::where('name','url')->value('value');
                
                $url = env('SITE_URL',$cdn);

                $url = $url . '/base/business/del';

                httpRequest($url,['id' => $business['id'],'avatar' => $data['avatar']]);
            }

            return $this->error('更新资料失败');
        }else{
            if(isset($data['avatar']) && $_FILES['avatar']['size'] > 0)
            {
                $cdn = ConfigModel::where('name','url')->value('value');

                $url = env('SITE_URL',$cdn);

                $url = $url . '/base/business/del';
                
                httpRequest($url,['id' => $business['id'],'avatar' => $business['avatar']]);
            }

            $business = BusinessModel::find($params['busid']);

            // $data = [
            //     'id' => $business['id'],
            //     'mobile' => $business['mobile'],
            //     'mobile_text' => $business['mobile_text'],
            //     'nickname' => $business['nickname'],
            //     'email' => $business['email'],
            //     'gender' => $business['gender'],
            //     'gender_text' => $business['gender_text'],
            //     'province' => $business['province'],
            //     'city' => $business['city'],
            //     'district' => $business['district'],
            //     'region_text' => $business['region_text'],
            //     'auth' => $business['auth'],
            //     'avatar_cdn' => $business['avatar_cdn']
            // ];
            $data = [
                'id' => $business['id'],
                'mobile' => $business['mobile'],
                'mobile_text' => $business['mobile_text'],
                'nickname' => $business['nickname'],
                'email' => $business['email'],
                'gender' => $business['gender'],
                'gender_text' =>$business['sex_text'],
                'province' => $business['province'],
                'city' => $business['city'],
                'district' => $business['district'],
                'region_text' => $business['region_text'],
                'auth' => $business['auth'],
                'avatar_cdn' => $business['avatar_cdn']
            ];

            return $this->success('更新资料成功',$data);
        }
    }

    
    // public function profile()
    // {
    //     $params = request()->input();
    //     $business = request()->get('business');
    //     // dd($business);
    //     // if($params['avatar'])
    //     // 组装数据
    //     $data = [
    //         'nickname' => trim($params['nickname']),
    //         'gender' => $params['gender']
    //     ];

    //     if($params['email'] != $business['email'])
    //     {
    //         $data['email'] = $params['email'];
    //         $data['auth'] = '0';
    //     }

    //     $password = $params['password'] ?? '';
    //     if(!empty($password))
    //     {
    //         $repass = md5($password . $business['salt']);

    //         if($repass === $business['password'])
    //         {
    //             return $this->error('新密码不能与原密码一致');
    //         }
    //         // dd($password);
    //         $salt = build_randstr();

    //         $data['password'] = md5($password . $salt);
    //         $data['salt'] = $salt;
    //     }
    //     // dd($password);
        
    //     // dd($params['code']);
    //     [$province,$city,$district] = explode(',',$params['code']);
    //     // dd($district);
    //     $path = RegionModel::where('code',$district)->value('parentpath');
    //     // dd($path);
    //     if(!$path)
    //     {
    //         return $this->error('所选地区不存在');
    //     }
    //     // dd($path);
    //     $data['province'] = $province ?? null;
    //     $data['city'] = $city ?? null;
    //     $data['district'] = $district ?? null;

    //     if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
    //     {
    //         $cdn = ConfigModel::where('name','url')->value('value');

    //         $url = $cdn . '/shop/business/upload';
    //         // return $url;
    //         // 第一个参数属于文件路径 第二个参数是文件类型 第三个是文件名
    //         // dd($params['id']);
    //         $file =  new \CURLFile($_FILES['avatar']['tmp_name'],$_FILES['avatar']['type'],$_FILES['avatar']['name']);

    //         $res = httpRequest($url,['avatar' => $file,'id' => $business['id']]);
    //         // var_dump($url);
    //         // return 1;
    //         // return $res;
    //         // dd($res);
    //         $avatar = json_decode($res,true);
    //         // dd($avatar);
    //         // return $avatar;
    //         if($avatar['code'] === 0)
    //         {
    //             return $this->error($avatar['msg']);
    //         }
    //         // return 1;
    //         // return $_FILES['avatar'];
    //         $data['avatar'] = $avatar['data'];
    //     }

    //     $result = BusinessModel::where('id',$params['busid'])->update($data);

    //     if($result !== false)
    //     {
    //         if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
    //         {
    //             $cdn = ConfigModel::where('name','url')->value('value');

    //             $url = $cdn . '/shop/business/del';
    //             httpRequest($url,['id' => $business['id'],'avatar' => $business['avatar']]);
    //         }

    //         $business = BusinessModel::find($params['busid']);

    //         // 建议直接调用Config模型查询
    //         $url = ConfigModel::where(['name' => 'url'])->value('value');

    //         $res = httpRequest($url . '/shop/business/avatar',['id' => $business['id']]);
    //         // return $res;
    //         $avatarData = json_decode($res,true);

    //         // $data = [
    //         //     'id' => $business['id'],
    //         //     'mobile' => $business['mobile'],
    //         //     'mobile_text' => $business['mobile_text'],
    //         //     'nickname' => $business['nickname'],
    //         //     'email' => $business['email'],
    //         //     'gender' => $business['gender'],
    //         //     'gender_text' =>$business['sex_text'],
    //         //     'province' => $business['province'],
    //         //     'city' => $business['city'],
    //         //     'district' => $business['district'],
    //         //     'region_text' => $business['region_text'],
    //         //     'auth' => $business['auth'],
    //         //     'avatar_cdn' => $business['avatar_cdn']
    //         // ];
            
    //         $data = [
    //             'id' => $business['id'],
    //             'mobile' => $business['mobile'],
    //             'mobile_text' => $business['mobile_text'],
    //             'nickname' => $business['nickname'],
    //             'email' => $business['email'],
    //             'gender' => $business['gender'],
    //             'gender_text' => $business['sex_text'],
    //             // 'gender_text' => $business['sex_text'],
    //             'province' => $business['province'],
    //             'city' => $business['city'],
    //             'district' => $business['district'],
    //             'region_text' => $business['region_text'],
    //             'auth' => $business['auth'],
    //             'avatar_cdn' => $avatarData['data']['avatar'],
    //             // 'avatar_cdn' => $$avatarData['data']['avatar_cdn']
    //         ];
    //         return $this->success('修改成功',$data);
    //     }else{
    //         if(isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0)
    //         {
    //             $cdn = ConfigModel::where('name','url')->value('value');

    //             $url = $cdn . '/shop/business/del';
    //             httpRequest($url,['id' => $business['id'],'avatar' => $data['avatar']]);
    //         }
    //         return $this->error('修改失败');
    //     }
    //     // return $data['avatar'];
    // }
    // public function profile()
    // {
    //     return 111;
    // }
}
